import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

///本地存储工具类
class LocalStorage {
  LocalStorage._();

  static final LocalStorage _singleton = LocalStorage._();

  ///工厂单例
  factory LocalStorage() => _singleton;

  ///检查是否存在键
  Future<bool> hasKey(final String key) =>
      SharedPreferences.getInstance().then((prefs) {
        if (key.isNotEmpty) {
          return prefs.containsKey(key);
        }
        return false;
      });

  static dynamic _fromJson(final String val) {
    try {
      return const JsonDecoder().convert(val);
    } catch (e) {
      return null;
    }
  }

  ///根据键获取数据
  Future<dynamic> getValByKey(final String key) =>
      SharedPreferences.getInstance().then((prefs) {
        if (key.isNotEmpty && prefs.containsKey(key)) {
          final val = prefs.get(key);
          if (val != null && val.runtimeType.toString() == "String") {
            final data = _fromJson(val.toString());
            return data ?? val;
          }
          return val;
        }
        return null;
      });

  ///保存数据
  Future<bool> save(final String key, final dynamic val) =>
      SharedPreferences.getInstance().then((prefs) {
        final String type;
        final dynamic data;
        if (val is Map || val is List) {
          type = "String";
          data = const JsonEncoder().convert(val);
        } else {
          type = val.runtimeType.toString();
          data = val;
        }
        switch (type) {
          case "String":
            return prefs.setString(key, data);
          case "int":
            return prefs.setInt(key, data);
          case "double":
            return prefs.setDouble(key, data);
          case "bool":
            return prefs.setBool(key, data);
        }
        return false;
      });

  ///清空键数据
  Future<void> clean(final String key) =>
      SharedPreferences.getInstance().then((prefs) {
        if (key.isNotEmpty && prefs.containsKey(key)) {
          prefs.remove(key);
        }
      });
}

///本地存储单例
final localStorage = LocalStorage();
